package com.engineering.elink.xaservice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.recruit.CvdBaseInfoCo;
import com.engineering.elink.co.recruit.CvdDatabaseCo;
import com.engineering.elink.co.recruit.CvdJobIntentionCo;
import com.engineering.elink.co.recruit.EducationExperienceAddCo;
import com.engineering.elink.co.recruit.ProjectExperienceAddCo;
import com.engineering.elink.co.recruit.WorkExperienceAddCo;
import com.engineering.elink.common.ErrorType;
import com.engineering.elink.domain.recruit.CvDatabase;
import com.engineering.elink.domain.recruit.CvdEwpAddress;
import com.engineering.elink.domain.recruit.CvdLanguage;
import com.engineering.elink.domain.recruit.EducationExperience;
import com.engineering.elink.domain.recruit.Job;
import com.engineering.elink.domain.recruit.ProjectExperience;
import com.engineering.elink.domain.recruit.TargetCompany;
import com.engineering.elink.domain.recruit.VitaCollection;
import com.engineering.elink.domain.recruit.VitaDelivery;
import com.engineering.elink.domain.recruit.WorkExperience;
import com.engineering.elink.recruitdao.CvDatabaseMapper;
import com.engineering.elink.recruitdao.CvdEwpAddressMapper;
import com.engineering.elink.recruitdao.CvdLanguageMapper;
import com.engineering.elink.recruitdao.EducationExperienceMapper;
import com.engineering.elink.recruitdao.JobMapper;
import com.engineering.elink.recruitdao.ProjectExperienceMapper;
import com.engineering.elink.recruitdao.TargetCompanyMapper;
import com.engineering.elink.recruitdao.VitaCollectionMapper;
import com.engineering.elink.recruitdao.VitaDeliveryMapper;
import com.engineering.elink.recruitdao.WorkExperienceMapper;
import com.engineering.elink.util.CollectionUtil;
import com.engineering.elink.util.UUIDUtil;
import com.engineering.elink.xaservice.CvdDatabaseXaService;
import com.fasterxml.jackson.core.type.TypeReference;

@Service
public class CvdDatabaseXaServiceImpl implements CvdDatabaseXaService{
	
	@Autowired
	private CvDatabaseMapper cvDatabaseMapper;
	
	@Autowired
	private CvdLanguageMapper cvdLanguageMapper;
	
	@Autowired
	private WorkExperienceMapper workExperienceMapper;
	
	@Autowired
	private EducationExperienceMapper educationExperienceMapper;
	
	@Autowired
	private ProjectExperienceMapper projectExperienceMapper;
	

	@Autowired
	private JobMapper jobMapper;
	
	@Autowired
	private TargetCompanyMapper targetCompanyMapper;
	
	@Autowired
	private VitaDeliveryMapper vitaDeliveryMapper;
	
	@Autowired
	private VitaCollectionMapper vitaCollectionMapper;
	
	@Autowired
	private CvdEwpAddressMapper cvdEwpAddressMapper;
	
	

	@Override
	public void saveJobIntention(String cvdId, CvdJobIntentionCo jobIntentionCo, String userId) throws Exception {
		
		CvDatabase cvd=getCvDatabase(cvdId,userId);
			
		PropertyUtils.copyProperties(cvd, jobIntentionCo);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
		saveEwpAddress(jobIntentionCo.getEwpJsonStr(),cvd);
	}
	
	private void saveEwpAddress(String jsonStr,CvDatabase cvd){
		//保存期望工作地址
		if(StringUtils.isNotEmpty(jsonStr)){
			
			List<CvdEwpAddress> ewplList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<CvdEwpAddress>>(){});
			
			if(CollectionUtil.collectionIsNotEmpty(ewplList)){
				
				List<Integer> ewpIdList=cvdEwpAddressMapper.selectEwpByCvdIdList(cvd.getCvdId());
				
				for(CvdEwpAddress jl:ewplList){
					if(jl==null)continue;
					jl.setCvdId(cvd.getCvdId());
					
					if(jl.getEwpId()==null || jl.getEwpId().intValue()==0){
						jl.setEwpId(null);
						cvdEwpAddressMapper.insertSelective(jl); 
					}else{
						cvdEwpAddressMapper.updateByPrimaryKeySelective(jl);
						ewpIdList.remove(jl.getEwpId());
					}
				}
				//批量
				if(CollectionUtil.collectionIsNotEmpty(ewpIdList)){
					cvdEwpAddressMapper.deleteBatch(ewpIdList);
				}
				
			}
		}
	}
	
	
	private CvDatabase getCvDatabase(String cvdId,String userId){
		CvDatabase cvd=null;
		
		if(StringUtils.isEmpty(cvdId)){
			int count=cvDatabaseMapper.countCvdataByUserId(userId);
			if(count>0){
				cvd=cvDatabaseMapper.selectByUserId(userId);
			}else{
				cvd=new CvDatabase();
				cvd.setCvdId(UUIDUtil.getUUID());
				cvd.setUserId(userId);
				cvd.setCreatTime(new Date()); 
				cvDatabaseMapper.insertSelective(cvd);
			}
		}else{
			cvd=cvDatabaseMapper.selectByPrimaryKey(cvdId);
		}
		
		if(cvd==null)
			throw new RuntimeException(ErrorType.CVDATABASE_ERROR.getMsg());
		
		return cvd;
	}

	@Override
	public void saveBaseInfo(String cvdId, CvdBaseInfoCo baseInfoCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		PropertyUtils.copyProperties(cvd, baseInfoCo);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
		saveLanguage(baseInfoCo.getLanguageJsonStr(),cvd);
		
	}
	
	private void saveLanguage(String jsonStr,CvDatabase cvd){
		//简历语言
		if(StringUtils.isNotEmpty(jsonStr)){
			List<CvdLanguage> cvdlList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<CvdLanguage>>(){});
			
			if(CollectionUtil.collectionIsNotEmpty(cvdlList)){
				//
				List<Integer> list=cvdLanguageMapper.selectCvdLangByCvdIdList(cvd.getCvdId());
				
				for(CvdLanguage jl:cvdlList){
					if(jl==null)continue;
					jl.setCvdId(cvd.getCvdId());
					jl.setUserId(cvd.getUserId());
					if(jl.getClId()==null || jl.getClId().intValue()==0){
						jl.setClId(null);
						cvdLanguageMapper.insertSelective(jl); 
					}else{
						cvdLanguageMapper.updateByPrimaryKeySelective(jl);
						list.remove(jl.getClId());
					}
				}
				if(CollectionUtil.collectionIsNotEmpty(list)){
					cvdLanguageMapper.deleteBatch(list);
				}
				
			}
		}
	}

	@Override
	public void saveWorkExperience(String cvdId, String jsonStr, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		saveWork(jsonStr,cvd);
		
		
	}
	
	private void saveWork(String jsonStr,CvDatabase cvd){
		if(StringUtils.isNotEmpty(jsonStr)){
			List<WorkExperience> weList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<WorkExperience>>(){});
			
			if(CollectionUtil.collectionIsNotEmpty(weList)){
				for(WorkExperience jl:weList){
					if(jl==null)continue;
					jl.setCvdId(cvd.getCvdId());
					
					if(jl.getWeId()==null || jl.getWeId().intValue()==0){
						jl.setWeId(null);
						workExperienceMapper.insertSelective(jl); 
					}else{
						workExperienceMapper.updateByPrimaryKeySelective(jl);
					}
				}
			}
		}
	}

	@Override
	public void saveEducationExperience(String cvdId, String jsonStr, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
	
		saveEdu(jsonStr,cvd);
	}
	
	private void saveEdu(String jsonStr,CvDatabase cvd){
		if(StringUtils.isNotEmpty(jsonStr)){
			List<EducationExperience> weList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<EducationExperience>>(){});
			
			if(CollectionUtil.collectionIsNotEmpty(weList)){
				for(EducationExperience jl:weList){
					if(jl==null)continue;
					jl.setCvdId(cvd.getCvdId());
					
					if(jl.getEeId()==null || jl.getEeId().intValue()==0){
						jl.setEeId(null);
						educationExperienceMapper.insertSelective(jl); 
					}else{
						educationExperienceMapper.updateByPrimaryKeySelective(jl);
					}
				}
			}
		}
	}

	@Override
	public void saveProjectExperience(String cvdId, String jsonStr, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		saveProject(jsonStr,cvd);
	}
	
	private void saveProject(String jsonStr,CvDatabase cvd){
		if(StringUtils.isNotEmpty(jsonStr)){
			List<ProjectExperience> weList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<ProjectExperience>>(){});
			
			if(CollectionUtil.collectionIsNotEmpty(weList)){
				for(ProjectExperience jl:weList){
					if(jl==null)continue;
					jl.setCvdId(cvd.getCvdId());
					
					if(jl.getPeId()==null || jl.getPeId().intValue()==0){
						jl.setPeId(null);
						projectExperienceMapper.insertSelective(jl); 
					}else{
						projectExperienceMapper.updateByPrimaryKeySelective(jl);
					}
				}
			}
		}
	}

	@Override
	public void saveCvdDatabase(CvdDatabaseCo co, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(co.getCvdId(),userId);
		
		PropertyUtils.copyProperties(cvd, co.getBaseInfoCo());
		PropertyUtils.copyProperties(cvd, co.getJobIntentionCo());
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
		saveLanguage(co.getBaseInfoCo().getLanguageJsonStr(),cvd);
		
		saveWork(co.getWorkJsonStr(),cvd);
		
		saveEdu(co.getEduJsonStr(),cvd);
		
		saveProject(co.getProjectJsonStr(),cvd);
		
	}

	@Override
	public void saveTargetJob(String[] array, String userId) throws Exception {
		List<Integer> list=targetCompanyMapper.selectMyTargetJobList(userId);
		
		TargetCompany tc=null;
		Job job=null;
		
		List<Integer> rvList=new ArrayList<Integer>();
		List<TargetCompany> addList=new ArrayList<TargetCompany>();
		for(String jobId:array){
			if(StringUtils.isEmpty(jobId))continue;
			
			job=jobMapper.selectByPrimaryKey(jobId);
			if(job==null){
				throw new RuntimeException(ErrorType.JOB_ERROR.getMsg());
			}
			
			tc=targetCompanyMapper.selectMyTargetJob(jobId, userId);
			if(tc==null){
				tc=new TargetCompany();
				tc.setJobId(jobId);
				tc.setUserId(userId);
				tc.setCompanyId(job.getCompanyId());
				tc.setType(0);
				
				addList.add(tc);
				
				//targetCompanyMapper.insertSelective(tc);
			}else{
				list.remove(tc.getTcId());
				rvList.add(tc.getTcId());
			}
		}
		
		if((list.size()+addList.size())>3){
			throw new RuntimeException("最多只能选择3个意向公司，您取消["+rvList.size()+"]个意向公司，您还可选择["+(3-list.size())+"]个意向公司！");
		}
		
		//批量删除
		if(CollectionUtil.collectionIsNotEmpty(rvList)){
			targetCompanyMapper.deleteBatchByTcId(rvList);
		}
		
		if(CollectionUtil.collectionIsNotEmpty(addList)){
			for(TargetCompany tcInfo:addList){
				targetCompanyMapper.insertSelective(tcInfo);
			}
		}
		
	}

	@Override
	public void batchMoveCvd(String vdIds, String userId) throws Exception {
		String[] array=StringUtils.split(vdIds,',');
		VitaDelivery vd=null;
		List<VitaCollection> vcList=new ArrayList<VitaCollection>();
		for(String vdId:array){
			if(StringUtils.isEmpty(vdId))continue;
			vd=vitaDeliveryMapper.selectByPrimaryKey(Integer.valueOf(vdId));
			if(vd==null){
				throw new RuntimeException(ErrorType.CVD_VITA_DELIVERY_ERROR.getMsg());
			}
			vcList.add(new VitaCollection(vd.getCompanyId(),vd.getCvdId(),vd.getJobId(),vd.getType()));
		}
		
		//批量
		vitaCollectionMapper.insertBatch(vcList);
		
		vitaDeliveryMapper.updateBatchByType(4,array);
		
	}

	@Override
	public void saveWorkExp(String cvdId, WorkExperienceAddCo workCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		WorkExperience we=new WorkExperience();
		PropertyUtils.copyProperties(we, workCo);
		
		we.setCvdId(cvd.getCvdId());
		
		this.workExperienceMapper.insertSelective(we);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
	}
	
	@Override
	public void updateWorkExp(String cvdId,Integer weId, WorkExperienceAddCo workCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		WorkExperience we=this.workExperienceMapper.selectByPrimaryKey(weId);
		if(we==null)
			throw new RuntimeException("工作经验信息不存在！");
		
		PropertyUtils.copyProperties(we, workCo);
		
		we.setCvdId(cvd.getCvdId());
		
		this.workExperienceMapper.updateByPrimaryKeySelective(we);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
	}

	@Override
	public void saveEduExp(String cvdId, EducationExperienceAddCo eeCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		EducationExperience ee=new EducationExperience();
		PropertyUtils.copyProperties(ee, eeCo);
		
		ee.setCvdId(cvd.getCvdId());
		
		this.educationExperienceMapper.insertSelective(ee);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
	}

	@Override
	public void updateEduExp(String cvdId, Integer eeId, EducationExperienceAddCo eeCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		EducationExperience ee=this.educationExperienceMapper.selectByPrimaryKey(eeId);
		if(ee==null)
			throw new RuntimeException("教育经历信息不存在！");
		
		PropertyUtils.copyProperties(ee, eeCo);
		
		ee.setCvdId(cvd.getCvdId());
		
		this.educationExperienceMapper.updateByPrimaryKeySelective(ee);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
	}

	@Override
	public void saveProjectExp(String cvdId, ProjectExperienceAddCo peCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		ProjectExperience pe=new ProjectExperience();
		PropertyUtils.copyProperties(pe, peCo);
		
		pe.setCvdId(cvd.getCvdId());
		
		this.projectExperienceMapper.insertSelective(pe);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
	}

	@Override
	public void updateProjectExp(String cvdId, Integer peId, ProjectExperienceAddCo peCo, String userId) throws Exception {
		CvDatabase cvd=getCvDatabase(cvdId,userId);
		
		ProjectExperience pe=this.projectExperienceMapper.selectByPrimaryKey(peId);
		if(pe==null)
			throw new RuntimeException("项目经验信息不存在！");
		
		PropertyUtils.copyProperties(pe, peCo);
		
		pe.setCvdId(cvd.getCvdId());
		
		this.projectExperienceMapper.updateByPrimaryKeySelective(pe);
		
		cvd.setUpdateTime(new Date());
		
		cvDatabaseMapper.updateByPrimaryKeySelective(cvd);
		
	}

	@Override
	public void updateBatchJob(String[] jobIds) throws Exception {
		
		//更新职位
		jobMapper.updateBatchByDeleteStatus(jobIds);
		
		//更新意向
		List<Integer> tList=targetCompanyMapper.selectTCByJobId(jobIds, 0);
		if(CollectionUtil.collectionIsNotEmpty(tList)){
			targetCompanyMapper.updateBatchByType(tList);
		}
		
		//更新最新简历
		List<Integer> vdList=vitaDeliveryMapper.selectViDeByJobId(jobIds, 5);
		if(CollectionUtil.collectionIsNotEmpty(vdList)){
			vitaDeliveryMapper.updateBatchByTypeList(5, vdList);
		}
		
		//更新简历库
		List<Integer> vcList=this.vitaCollectionMapper.selectViCoByJobId(jobIds, 4);
		if(CollectionUtil.collectionIsNotEmpty(vcList)){
			vitaCollectionMapper.updateBatchByStatusList(4, vcList);
		}
	}
	
}
